<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <!--因为有跳转BUG所有当点击查询应该会到第一页-->
          <el-button type="primary" v-on:click="deptQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表:优秀实践，copy domain修改列表-->
    <el-table :data="roles" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="220" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="编码" width="180" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="编码" width="180" sortable>
      </el-table-column>
      <el-table-column label="操作" >
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <!-- v-perm="'role:delete'" -->
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="totals"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增和编辑对话框-->
    <el-dialog :title="title"  :visible.sync="editFormVisible" :close-on-click-modal="false">
      <!--ref="editForm" 指定表单名称，以后可以通过this.$refs.roleForm-->
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="分配菜单" prop="roles">
          <el-cascader v-model="editForm.roles" clearable
                       placeholder="试试搜索：指南"
                       :options="menuTree"
                       :props="{
									multiple: true,
								 	label:'name',
									value:'id'
								 }"
                       filterable></el-cascader>
        </el-form-item>
        <el-form-item label="分配权限" prop="permissions">
          <el-select v-model="editForm.permissions" multiple placeholder="请选择">
            <el-option
                v-for="item in permissionList"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">保存</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>

export default {
  data() {
    return {
      deptTree: [],
      // 标题
      title: '',
      filters: {
        name: ''
      },
      employees: [],
      roles: [],
      totals: 0,
      currentPage: 1,
      pageSize: 10,
      listLoading: false,
      sels: [],//列表选中列

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      editForm: {
        id: null,
        name: '',
        sn: '',
        menus: null,
        permissions: null
      },
    }
  },
  methods: {
    // 获取级联数据
    getDeptTree() {
      this.$http.get("/dept/deptTree")
          .then(result => {
            this.deptTree = result.data
          }).catch(result => {

      })

    },
    // 获取部门列表
    getEmployee() {
      // 前端封装了一个对象到后端分页
      // 发送axios请求
      this.$http.get("/emp")
          .then(result => {
            this.employees = result.data;
          })
    },
    //性别显示转换
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getRole();
    },
    // 查询数据从第一页开始
    deptQuery() {
      this.currentPage = 1;
      this.getRole();
    },
    //获取用户列表
    getRole() {
      // 前端封装了一个对象到后端分页
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        // 从工具条中获取到keywords的值
        keywords: this.filters.name // 高级查询数值获取
        // name: this.filters.name
      };
      this.listLoading = true;
      // 发送axios请求
      this.$http.post("/role/list", para).then(result => {
        this.roles = result.data.rows;
        this.totals = result.data.totals;
        this.listLoading = false;
      }).catch(result => {
        this.$message.error('系统繁忙，请稍后重试!!!');
      })
    },
    //删除请求
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/role/" + row.id)
            .then(result => {
              if (result.data.success) {
                this.$message({
                  message: result.data.msg,
                  type: 'success'
                });
                this.currentPage = 1;
                this.getRole();
              } else {
                this.$message({
                  message: result.data.msg,
                  type: 'error'
                });
              }
              this.currentPage = 1;
              this.getRole();
            })
            .catch(result => {
              this.listLoading = false;
              this.$message({
                message: '操作失败',
                type: 'error'
              });
            })
      }).catch(() => {
      });
    },
    //显示编辑模态框界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
      this.getEmployee();
      this.getDeptTree();
    },
    //显示新增模态框界面
    handleAdd: function () {
      this.editFormVisible = true;
      this.getEmployee();
      this.getDeptTree();
      this.title = '新增',
          this.editForm = {
            id: null,
            name: '',
            sn: '',
            menus: null,
            permissions: null
          };
    },
    //新增编辑提交请求（因为后端合并了新增修改所以只用发送请求后端判断）
    editSubmit: function () {
      // 数据校验请求
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            let para = Object.assign({}, this.editForm);
            // 获取表格中的父亲字段
            let arr = para.parent_id
            // 后端是Long类型的字段接收 那么给后端的值就是空的
            if (arr && arr.length == null){
                para.parent_id = null;
            }
            if (arr && arr.length > 0){
              para.parent_id = arr[arr.length-1];
            }
            this.$http.put("/role", para)
                .then(result => {
                  if (result.data.success) {
                    this.$message({
                      message: result.data.msg,
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: result.data.msg,
                      type: 'error'
                    });
                  }
                  //在请求数据时关闭忙等框
                  this.editLoading = false;
                  this.editFormVisible = false;
                  this.getRole();
                })
                .catch(result => {
                  this.listLoading = false;
                  this.$message({
                    message: '操作失败',
                    type: 'error'
                  });
                })

          });
        }
      });
    },
    //列表选择列
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/role", ids)
            .then(result => {
              if (result.data.success) {
                this.$message({
                  message: result.data.msg,
                  type: 'success'
                });

              } else {
                this.$message({
                  message: result.data.msg,
                  type: 'error'
                });
              }
              this.currentPage = 1;
              this.getRole();
            })
            .catch(result => {
              this.listLoading = false;
              this.$message({
                message: '操作失败',
                type: 'error'
              });
            })
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getRole();
    // this.getEmployee();
  }
}

</script>

<style scoped>

</style>